package com.example.springmvcdemo3;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RequestMapping("/session")
@RestController
public class SessionController{
    @RequestMapping("/getC")
    public String getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            Arrays.stream(cookies).forEach((ck)->{
                System.out.println("name:"+ck.getName()+"val:"+ck.getValue());
            });
        }
        return "获取cookie成功";
    }
    @RequestMapping("/getC2")
    public String getCookie2(@CookieValue("bite")String bite ){
        return bite;
    }

    @RequestMapping("/setSess")
    public String setSess(HttpServletRequest request){
        //从cookie中拿到了sessionID，然后根据sessionID获取到了Session对象,如果没有获取到，会创建一个Session对象
        HttpSession session = request.getSession();
        session.setAttribute("name","zhangsan");
        return "设置Session成功";
    }

    @RequestMapping("/getSess")
    public String getSess(HttpServletRequest request){
        //从cookie中拿到了sessionID，然后根据sessionID获取到了Session对象
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        return "从session中获取name："+name;
    }
    @RequestMapping("/getSess2")
    public String getSess2(HttpSession session){
        String name = (String) session.getAttribute("name");
        return  "从session中获取name:"+name;
    }
    @RequestMapping("/getSess3")
    public String getSess(@SessionAttribute("name")String name){
        return  "从session中获取name:"+name;
    }
    @RequestMapping("/getH")
    public String getHeader(HttpServletRequest request){
        String UserAgent = request.getHeader("User-Agent");
        return "从header中获取User-Agent："+UserAgent;
    }
    @RequestMapping("/getH2")
    public String getHeader(@RequestHeader("User-Agent")String UserAgent){
        return "从header中获取User-Agent："+UserAgent;
    }
}
